package com.kele.pc;

import java.util.Date;

/**
 * @author kele
 * @date 2021/10/9 16:28
 * @description synchronized生产者
 */
public class SynchronizedProduct {

    public static void main(String[] args) {

        Data data=new Data();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                try {
                    data.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                try {
                    data.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                try {
                    data.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                try {
                    data.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();


    }
}

class Data{

    private int data=0;
    public synchronized void add() throws InterruptedException {
        while (data!=0){
            this.wait();
        }
        data++;
        System.out.println(Thread.currentThread().getName()+"=>"+data);
        this.notify();
    }

    public synchronized void dec() throws InterruptedException {
        while (data==0){
            this.wait();
        }
        data--;
        System.out.println(Thread.currentThread().getName()+"=>"+data);
        this.notify();
    }
}


